package com.controller;


import com.DTO.AddGroupQuery;
import com.DTO.GroupDTO;
import com.Exception.NormalException.FileExceptions.FileFormatException;
import com.Factory.UserFactory;
import com.Result.UserWithRelation;
import com.baomidou.mybatisplus.annotation.TableName;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.entity.Group;
import com.entity.GroupApply;
import com.entity.GroupUser;
import com.entity.User;
import com.service.GroupApplyService;
import com.service.GroupService;
import com.service.GroupUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import org.springframework.stereotype.Controller;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.HashSet;
import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author XTC
 * @since 2024-07-10
 */
    @CrossOrigin
    @RestController
    @RequestMapping("/group")
    @Api(tags = "群聊管理器")
    public class GroupController {
        @Autowired
        private GroupService groupService;

        @Autowired
        private GroupUserService groupUserService;

        @Autowired
        private UserFactory userFactory;

        @PostMapping("/add")
        @ApiOperation(value = "新建群聊")
        public boolean add(@RequestBody AddGroupQuery addGroupQuery) {
            Group group = new Group();
            BeanUtils.copyProperties(addGroupQuery, group);
            group.setSetTime(new Date());
            if(!addGroupQuery.getUserIdList().contains(addGroupQuery.getMasterId())) {

            }
            groupService.add(group);
            return this.groupUserService.addUsersToGroup(group.getId(), addGroupQuery.getUserIdList());
        }

        @GetMapping("/getAll")
        @ApiOperation(value = "获取所有群聊")
        public List<Group> getAll() {
            return this.groupService.list();
        }

        @GetMapping("/getAllUser")
        @ApiOperation(value = "获取群聊中的所有用户")
        public List<User> getAllUser(Integer groupId) {
            return this.groupUserService.getAllUserOfGroup(groupId);
        }

        @GetMapping("/getAllUserWithRelation")
        @ApiOperation(value = "获取群聊中的用户，并标注当前用户与他们的关系")
        public List<UserWithRelation> getAllUserWithRelatino(Integer groupId, Integer userId) {
            List<User> userList = this.groupUserService.getAllUserOfGroup(groupId);
            return this.userFactory.getUserWithRelationList(userList, userId);
        }

        @GetMapping("/exitGroup")
        @ApiOperation(value = "退出群聊")
        public boolean exitGroup(Integer groupId, Integer userId)  {
            QueryWrapper<GroupUser> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("user_id",userId).eq("group_id",groupId);
            return this.groupUserService.remove(queryWrapper);
        }

        @GetMapping("/delete")
        @ApiOperation(value = "删除群聊", notes = "返回删除结果")
        public boolean delete(Integer groupId) {
            return this.groupService.delete(groupId);
        }

        @PostMapping("/update")
        @ApiOperation(value = "修改群聊信息", notes = "不可修改群聊头像和创建时间\n不需要修改的参数不传递")
        public boolean update(@RequestBody Group group) {
            LambdaUpdateWrapper<Group> wrapper = new LambdaUpdateWrapper<>();
            wrapper.eq(Group::getId, group.getId())
                    .set(group.getName() != null, Group::getName, group.getName())
                    .set(group.getIntroduce() != null, Group::getIntroduce, group.getIntroduce())
                    .set(group.getMasterId() != null, Group::getMasterId, group.getMasterId());
            return this.groupService.update(wrapper);
        }

        @GetMapping("/getById")
        @ApiOperation(value = "根据id精确获取群聊")
        public Group getById(Integer groupId) {
            return this.groupService.getById(groupId);
        }

        @GetMapping("/getAllJoinedGroup")
        @ApiOperation(value = "获取用户加入的群聊")
        public List<Group> getAllJoinedGroup(Integer userId) {
            return this.groupUserService.getAllJoinedGroup(userId);
        }

        @PostMapping("/uploadHead")
        @ApiOperation(value = "上传头像", notes = "返回头像url")
        @ApiResponses({
                @ApiResponse(code = FileFormatException.code, message = FileFormatException.message)
        })
        public String uploadHead(Integer groupId, MultipartFile head, HttpServletResponse response) {
            try {
                return this.groupService.uploadHead(groupId, head);
            } catch (FileFormatException e) {
                e.setStatus(response);
                return null;
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }

